package com.gzdict.common.ext

import android.text.Editable
import android.text.TextWatcher
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.gzdict.common.R

/**
 * 描述: 基本控件扩展
 * @author: create by shang
 * date:2024/3/6 0006 14
 */


/**
 * 图片控件渲染
 */
fun ImageView.url(
    path: String?,
    @DrawableRes placeholder: Int = R.mipmap.bg_load_default,
    @DrawableRes error: Int = R.mipmap.bg_load_default
) {

    if (path.isNullOrBlank()) {
        Glide.with(this)
            .load(error)
            .into(this)
        return
    }

    Glide.with(this)
        .load(path)
        .error(placeholder)
        .placeholder(error)
        .into(this)
}


/**
 * 带圆角图片
 * @param path 路径
 * @param radius 圆角半径 单位DP
 */
fun ImageView.roundedCorner(
    path: String?,
    radius: Float,
    @DrawableRes placeholder: Int = R.mipmap.bg_load_default,
    @DrawableRes error: Int = R.mipmap.bg_load_default
) {

    if (path.isNullOrBlank()) {
        Glide.with(this)
            .load(error)
            .into(this)
        return
    }

    val options =
        RequestOptions().transform(
            CenterCrop(),
            RoundedCorners(radius.dp(context).toInt())
        )
    Glide.with(this)
        .load(path)
        .apply(options)
        .error(placeholder)
        .placeholder(error)
        .into(this)
}


/**
 * 图片控件渲染 裁剪圆形图片
 * @param path 图片路径
 */
fun ImageView.circle(
    path: String?,
    @DrawableRes placeholder: Int = R.mipmap.bg_load_default,
    @DrawableRes error: Int = R.mipmap.bg_load_default
) {

    if (path.isNullOrBlank()) {
        Glide.with(this)
            .load(error)
            .into(this)
        return
    }

    val options =  RequestOptions().transform(CircleCrop())
    Glide.with(this)
        .load(path)
        .apply(options)
        .error(placeholder)
        .placeholder(error)
        .into(this)
}



/**
 * 文本监听
 */
fun TextView.addWatcher(isEmpty: (Boolean) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            isEmpty.invoke(!p0.isNullOrEmpty())
        }

        override fun afterTextChanged(p0: Editable?) {
        }

    })
}